/**
 * 游戏内邮件系统 - 简化版
 * 只包含标题、内容、附件和时间功能，使用单一数据库存储
 */
class GameEmailSystem {
    /**
     * 构造函数
     * @param {Object} database - 数据库实例 (支持基本的键值操作)
     */
    constructor(database) {
        this.database = database;
        this.mailboxPrefix = 'player_mailbox_';
    }

    /**
     * 发送邮件给单个玩家
     * @param {string} playerId - 玩家ID
     * @param {string} title - 邮件标题
     * @param {string} content - 邮件内容
     * @param {Object} attachment - 附件对象 (可选)
     */
    async sendMailToPlayer(playerId, title, content, attachment = null) {
        // 创建邮件对象
        const mail = {
            id: this._generateMailId(),
            title: title,
            content: content,
            attachment: attachment,
            timestamp: Date.now(),
            isRead: false,
            isAttachmentCollected: attachment ? false : true
        };

        // 获取玩家邮箱
        const mailbox = await this._getPlayerMailbox(playerId);

        // 添加新邮件
        mailbox.push(mail);

        // 保存到数据库
        return await this._savePlayerMailbox(playerId, mailbox);
    }

    /**
     * 批量发送邮件给多个玩家
     * @param {Array<string>} playerIds - 玩家ID数组
     * @param {string} title - 邮件标题
     * @param {string} content - 邮件内容
     * @param {Object} attachment - 附件对象 (可选)
     */
    async sendMailToPlayers(playerIds, title, content, attachment = null) {
        const promises = playerIds.map(playerId =>
            this.sendMailToPlayer(playerId, title, content, attachment)
        );

        return Promise.all(promises);
    }

    /**
     * 获取玩家的邮件列表
     * @param {string} playerId - 玩家ID
     * @param {number} page - 页码 (可选，默认1)
     * @param {number} pageSize - 每页数量 (可选，默认20)
     * @returns {Array} 邮件对象列表
     */
    async getPlayerMailList(playerId, page = 1, pageSize = 20) {
        const mailbox = await this._getPlayerMailbox(playerId);

        // 按时间倒序排序 (最新的邮件在前)
        mailbox.sort((a, b) => b.timestamp - a.timestamp);

        // 分页
        const startIndex = (page - 1) * pageSize;
        const endIndex = startIndex + pageSize;

        return mailbox.slice(startIndex, endIndex);
    }

    /**
     * 标记邮件为已读
     * @param {string} playerId - 玩家ID
     * @param {string} mailId - 邮件ID
     */
    async markMailAsRead(playerId, mailId) {
        const mailbox = await this._getPlayerMailbox(playerId);
        const mail = mailbox.find(m => m.id === mailId);

        if (mail) {
            mail.isRead = true;
            return await this._savePlayerMailbox(playerId, mailbox);
        }

        return false;
    }

    /**
     * 领取邮件附件
     * @param {string} playerId - 玩家ID
     * @param {string} mailId - 邮件ID
     * @returns {Object|null} 附件对象，如果没有附件或已领取则返回null
     */
    async collectAttachment(playerId, mailId) {
        const mailbox = await this._getPlayerMailbox(playerId);
        const mail = mailbox.find(m => m.id === mailId);

        if (mail && mail.attachment && !mail.isAttachmentCollected) {
            // 标记附件为已领取
            mail.isAttachmentCollected = true;
            await this._savePlayerMailbox(playerId, mailbox);

            return mail.attachment;
        }

        return null;
    }

    /**
     * 删除邮件
     * @param {string} playerId - 玩家ID
     * @param {string} mailId - 邮件ID
     */
    async deleteMail(playerId, mailId) {
        const mailbox = await this._getPlayerMailbox(playerId);
        const initialLength = mailbox.length;

        // 过滤掉要删除的邮件
        const filteredMailbox = mailbox.filter(m => m.id !== mailId);

        if (filteredMailbox.length !== initialLength) {
            await this._savePlayerMailbox(playerId, filteredMailbox);
            return true;
        }

        return false;
    }

    /**
     * 获取玩家邮箱
     * @private
     * @param {string} playerId - 玩家ID
     * @returns {Array} 邮件列表
     */
    async _getPlayerMailbox(playerId) {
        const key = `${this.mailboxPrefix}${playerId}`;
        const mailbox = await this.database.get(key);

        // 如果邮箱不存在，返回空数组
        return mailbox || [];
    }

    /**
     * 保存玩家邮箱
     * @private
     * @param {string} playerId - 玩家ID
     * @param {Array} mailbox - 邮件列表
     */
    async _savePlayerMailbox(playerId, mailbox) {
        const key = `${this.mailboxPrefix}${playerId}`;
        return await this.database.set(key, mailbox);
    }

    /**
     * 生成唯一邮件ID
     * @private
     * @returns {string} 唯一ID
     */
    _generateMailId() {
        return Date.now().toString(36) + Math.random().toString(36).substr(2, 5);
    }
}

// 使用示例
/**
// 假设已有数据库实例
const gameDatabase = getGameDatabase(); // 替换为实际的数据库获取方式

// 创建邮件系统实例
const emailSystem = new GameEmailSystem(gameDatabase);

// 发送邮件示例
async function example() {
  // 发送带附件的邮件
  await emailSystem.sendMailToPlayer(
    'player123',
    '节日礼包',
    '亲爱的玩家，感谢您的支持，祝您节日快乐！',
    { gold: 1000, items: [{ id: 'item001', count: 5 }] }
  );
  
  // 获取邮件列表
  const mails = await emailSystem.getPlayerMailList('player123');
  console.log(mails);
  
  // 领取附件
  const attachment = await emailSystem.collectAttachment('player123', mails[0].id);
  if (attachment) {
    console.log('领取附件成功:', attachment);
  }
}
*/

module.exports = GameEmailSystem;